package com.prp.gwt.client.user.mail;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Window;
import com.prp.gwt.client.ClientConstants;
import com.prp.gwt.client.Host;
import com.prp.gwt.client.vo.NewMail;
import com.prp.gwt.client.widgets.UserBarPanel;
import com.prp.gwt.client.widgets.mail.MailView;
import com.prp.gwt.client.widgets.mail.MassMailPanel;
import com.prp.gwt.client.widgets.mail.NewMailPanel;

public class MailHistoryHandler implements ValueChangeHandler<String> {

	public static final String OUTMAILLIST = "outmaillist";
	public static final String INMAILLIST = "inmaillist";
	public static final String NEWMAIL = "newmail";
	public static final String PREFIX_READMAIL = "readmail=";
	public static final String MASSMAIL = "massmail";
	public static final String INIT_VALUE = INMAILLIST;
	
	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		String token = event.getValue();
		if (token.equals(INMAILLIST)) {
			UserBarPanel.getInstance().selectTab(ClientConstants.INDEX_MAIL);
			//MailView.getInstance().setBarVisible(true);
			MailListener.getInstance().getInMainList();
			MailView.getInstance().showWidget(MailView.INMAILBOX);
			
		} else if (token.equals(OUTMAILLIST)) {
			UserBarPanel.getInstance().selectTab(ClientConstants.INDEX_MAIL);
			//MailView.getInstance().setBarVisible(true);
			MailListener.getInstance().getOutMailList(); 
			MailView.getInstance().showWidget(MailView.OUTMAILBOX);
			
		} else if (token.equals(NEWMAIL)) {
			UserBarPanel.getInstance().selectTab(ClientConstants.INDEX_MAIL);
			NewMailPanel.getInstance().Load(new NewMail());
			//MailView.getInstance().setBarVisible(false);
			MailView.getInstance().showWidget(MailView.NEWMAIL);
			
		} else if (token.startsWith(PREFIX_READMAIL)) {
			UserBarPanel.getInstance().selectTab(ClientConstants.INDEX_MAIL);
			try {
				//MailView.getInstance().setBarVisible(false);
				MailView.getInstance().showWidget(MailView.READINMAIL);
				int mailId = Integer.parseInt(token.substring(PREFIX_READMAIL
						.length()));
				MailListener.getInstance().getMail(mailId);
			} catch (NumberFormatException e) {
				Window.Location.replace(Host.getPAGE_NOT_FOUND());
			}
			
		}else if (token.equals(MASSMAIL)) {
			UserBarPanel.getInstance().selectTab(ClientConstants.INDEX_MAIL);
			MassMailPanel.getInstance().Load(new NewMail());
			//MailView.getInstance().setBarVisible(false);
			MailView.getInstance().showWidget(MailView.MASSMAIL);
		}
	}
}
